package cn.hj.basic.util;

import cn.hj.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 *登录上下文
 * 登录人信息
 */
public class LoginContext {


    /**
     * 获取当前登录人
     * @return
     */
    public static Logininfo getCurrentLogininfo(HttpServletRequest request){
        //在请求头里拿到token
        String token = request.getHeader("token");
        //token不为空
        if(!StringUtils.isEmpty(token)){
            //在非受容器管理对象里拿受容器管理对象(springmvc提供的工具类,先拿到容器)
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            //在通过容器拿到容器中的对象
            RedisTemplate redisTemplate = (RedisTemplate)webApplicationContext.getBean("redisTemplate");
            //从redis中查询数据
            Object loginTmp = redisTemplate.opsForValue().get(token);
            if (loginTmp!=null){
                return (Logininfo)loginTmp;
            }
        }
        return null;
    }
}
